// 云函数入口文件
const cloud = require("wx-server-sdk")
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV});
const db = cloud.database();
const CustomError = require("./CustomError");

// 云函数入口函数
exports.main = async (event, context) => {
    switch (event.actionName) {
        case "getUserInfo":
            return await getUserInfo(event)
        case "addBrowsingRecords":
            return await addBrowsingRecords(event)
        case "getHelperCount":
            return await getHelperCount(event)
        case "updateUsrInfo":
            return await updateUsrInfo(event)
        case "addFeedback":
            return await addFeedback(event)
        case "getPhoneNumber":
            return await getPhoneNumber(event)
    }
}

/*
* 获取用户信息
* */
async function getUserInfo(event) {
    try {
        let {OPENID} = cloud.getWXContext();
        let userInfo = await db.collection("user").where({
            openId: OPENID
        }).get()
        if (userInfo.data.length > 0) { //有记录 直接返回
            return {data: userInfo.data[0], status: 0};
        } else {
            let res = await db.collection("user").add({
                data: {
                    openId: OPENID,
                    createTime: new Date().getTime(),
                }
            })
            return {
                data: {_id: res._id, openId: OPENID},
                status: 0
            }
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 更新用户信息
* */
async function updateUsrInfo(event) {
    try {
        delete event.actionName;
        if (Object.keys(event.params).length === 0) {throw new Error("参数不能为空")}
        let {OPENID} = cloud.getWXContext();
        let collection = await db.collection("user").where({
            openId: OPENID
        })
        await collection.update({
            data: event.params
        })
        let res = await collection.get()
        return {
            data: res.data[0],
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 增加用户浏览记录
* */
async function addBrowsingRecords(event) { //rId为浏览内容id
    try {
        const _ = db.command;
        let {rid, sharerId} = event.params;
        let {OPENID} = cloud.getWXContext();
        let collection = await db.collection("browse");
        let browse = await collection.where({ //查询浏览记录  每个用户只有浏览一篇文章只记录一次
            rid: rid,
            openId: OPENID
        }).get()
        if (browse.data.length > 0) { //如果有记录
            return {status: 0, data: browse.data}
        } else {
            let addParams = {rid: rid, openId: OPENID};
            if (sharerId && sharerId !== OPENID) { //自己享给自己 不记录
                addParams.sharerId = sharerId;
                db.collection("record").doc(rid).update({ //更新浏览 分享记录
                    data: {
                        views: _.inc(1),
                        shares: _.inc(1)
                    }
                }).catch(function (e) {
                    console.error("======addBrowsingRecords record update======");
                    console.error(e);
                    throw e
                })
            } else {
                db.collection("record").doc(rid).update({ //更新浏览记录
                    data: {
                        views: _.inc(1)
                    }
                }).catch(function (e) {
                    console.error("======addBrowsingRecords record update======");
                    console.error(e);
                    throw e
                })
            }
            await collection.add({data: addParams});
            return {status: 0}
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 获取助力值
* */
async function getHelperCount(event) {
    try {
        let {OPENID} = cloud.getWXContext();
        let res = await db.collection("browse").where({
            sharerId: OPENID,
        }).count();
        return {
            status: 0,
            data: {total: res.total}
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 问题反馈
* */
async function addFeedback(event) {
    try {
        let {params} = event;
        let {OPENID} = cloud.getWXContext();
        let res = await db.collection("feedback").add({
            data: Object.assign(params, {
                complete: 0, //0 完成状态  /未完成 1已完成
                verify: 0, //审核状态  /0审核中 1已通过 2未通过
                openId: OPENID,
                createTime: new Date().getTime(),
            })
        })
        return {
            data: {_id: res._id},
            status: 0
        };
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}

/*
* 获取微信绑定手机号
* */
async function getPhoneNumber (event) {
    try {
        let {cloudID} = event.params
        const {OPENID} = cloud.getWXContext();
        const res = await cloud.getOpenData({list: [cloudID]});
        const phoneNumber = res.list[0].data.phoneNumber
        await db.collection("user").where({
            openId: OPENID
        }).update({
            data: {phone: phoneNumber}
        })
        return {
            data: res.list[0].data,
            status: 0
        }
    } catch (e) {
        console.error("======" + event.actionName + "======");
        console.error(e)
        return new CustomError(e, event.actionName)
    }
}